<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/14 0014
 * Time: 下午 5:31
 */
namespace app\api\controller;

use think\Request;

class Repurchase extends Base{
    /**
     * 获取订单可加价换购的商品
     * @param Request $request
     * @return \think\response\Json
     */
    public function getRepurchaseProduct(Request $request){
        $param = $request->param();
        $order_total = $param['order_total'];
        $member_id = $param['member_id'];
        $where = [
            'threshold' => ['elt', $order_total],
            'status' => 1
        ];
        $Repurchase = \app\admin\model\Repurchase::where($where)->select();
        if($Repurchase){
            $Member = \app\admin\model\Member::where('id',$member_id)->field('member_level_id,level_end_time')->find();
            if($Member || !$member_id){
                $product_ids = [];
                foreach ($Repurchase as $v){
                    if($v['to_user_type'] == 2){
                        $member_levelarr = explode(',',$v['to_users']);
                        if(in_array($Member['member_level_id'],$member_levelarr)){
                            if($Member->member_level_id != 1){
                                $nowtime = time();
                                $level_end_time = strtotime($Member->level_end_time);
                                if($nowtime < $level_end_time){
                                    array_push($product_ids,$v['product_id']);
                                }
                            }else{
                                array_push($product_ids,$v['product_id']);
                            }
                        }
                    }else{
                        array_push($product_ids,$v['product_id']);
                    }
                }
                $Products = \app\admin\model\Product::where('id','in',$product_ids)->field('id,name,price,img_url,spec,unit,describe')->select();
                foreach ($Products as &$v){
                    foreach ($Repurchase as $value){
                        if($v['id'] == $value['product_id']){
                            $v['markup'] = $value['markup'];
                            $v['limit_num'] = $value['limit_num'];
                            $v['qty'] = \app\admin\model\Product::getStock($v['id']);
                        }
                    }
                }
                return show(config('status.SUCCESS_STATUS'),'ok',$Products);
            }else{
                return show(config('status.ERROR_STATUS'),'用户异常',NULL);
            }
        }else{
            return show(config('status.SUCCESS_STATUS'),'暂无数据',NULL);
        }

    }
}